package com.sg.java;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sg.java.apps.ReadHdfsFile;
import com.sg.java.constant.Constant;
import com.sg.java.entity.*;
import com.sg.java.enums.VoltageLevelEnum;
import com.sg.java.util.*;
import lombok.extern.log4j.Log4j;
import org.stringtemplate.v4.ST;
import redis.clients.jedis.Jedis;


import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


/**
 * @author lhy
 * @date 2022/7/21 9:43
 */

@Log4j
public class YHVolt4 implements Serializable {


    private static YHVolt4 yhVolt;
    private static List<Integer> pointList = null;

    //电压等级
    private static ConcurrentHashMap<String, Double> acMap = new ConcurrentHashMap<>();

    //配变电压等级
    private static ConcurrentHashMap<String, Double> pbacMap = new ConcurrentHashMap<>();

    //严重越上
    private static ConcurrentHashMap<String, Double> yzpbMap = new ConcurrentHashMap<>();

    //有效数据越上限越下限阈值
    private static ConcurrentHashMap<String, Double> effectiveDataMap = new ConcurrentHashMap<>();


    private static ConcurrentHashMap<String, String> meterIdMap = new ConcurrentHashMap<>();

    //用户关联关系
    private static ConcurrentHashMap<String, String> yhMap = new ConcurrentHashMap<>();

    //用户和配变关系
//    private static ConcurrentHashMap<String, String> yhPidMap = new ConcurrentHashMap<>();

    //配变测点关系
    private static ConcurrentHashMap<String, String> pbGxMap = new ConcurrentHashMap<>();

    private static boolean flag = true;

    public static final String pbgx = "pbgx111";
    public static final String yhgx = "yhgx111";
    public static final String yhpb = "yhTopb111";

//    @SneakyThrows
//    public static YHVolt getInstance() {
//        if (yhVolt == null) {
//            synchronized (YHVolt.class) {
//                if (yhVolt == null) {
//                    yhVolt = new YHVolt();
//                    log.info("加载关系");
//                    String pbgx = "20220806pbgx111";
//                    String yhgx = "20220806yhgx111";
////                    JedisUtils.InitJedisPool("25.64.41.53", 6379, 100000, "Huawei@169");
////                    jp = JedisUtils.getJp();
//                    readProperties(pbgx, yhgx);
//                }
//            }
//        }
//        return yhVolt;
//    }


//    public static void initReadProperties() {
//        try {
//            String acPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "ac.properties";
//            PropertiesUtils.readProperties(acPath, acMap);
//
//            String pbacPath2 = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "pbac.properties";
//            PropertiesUtils.readProperties(pbacPath2, pbacMap);
//
//            //配变用户严重阈值
//            String yzpbPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "yzpb.properties";
//            PropertiesUtils.readProperties(yzpbPath, yzpbMap);
//
//            // 读取有效数据上限和下限
//            String effectiveDataPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "effectiveData.properties";
//            PropertiesUtils.readProperties(effectiveDataPath, effectiveDataMap);
//
//
//            String[] pbHeaders  = new String[]{"cdId", "pbId", "volt_code", "tran_name", "org_no", "grid_type", "equip_id", "edrl", "sbxh", "tyrq"};
//            String   pbFilePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
//            //填充用户和台区的关系map
//            yhPidMap = CsvUtils.CsvToPb(pbFilePath, pbHeaders, yhpb);
//            log.info("加载完成用户台区关系: " + yhPidMap.size());
//
//            //填充配变到测点的关系map
//            pbGxMap = CsvUtils.CsvToPbCd(pbFilePath, pbHeaders, pbgx, null);
//            log.info("加载完成配变测点关系: " + pbGxMap.size());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static VoltageQualifiedVo getResult(CMS_VOLT_CURVE curve, String ds) {

        //测点id
        if (curve.getMETER_ID().equals("8000000038607271")) {
            String cdId = Optional.ofNullable(curve.getMETER_ID())
                    .orElse(null);
            if (meterIdMap.get(cdId) == null) {
                meterIdMap.put(cdId, "");
            } else {
                return null;
            }

            if (flag) {
                String pbgx = ds + "pbgx111";
                String yhgx = ds + "yhgx111";
                String yhpb = ds + "yhTopb111";
                try {
                    readProperties(pbgx, yhgx, yhpb);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                flag = false;
            }


            Integer[] $24 = {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93};

            pointList = Arrays.asList($24);
            String logId = "";
            VoltageQualifiedVo vo = null;
            //初始化公共对象
            VoltageQualified voltageQualified = EntityUtils.initVoltageQualified();

            //越上限电压数组
            StringBuilder upBuilder = new StringBuilder();
            StringBuilder downBuilder = new StringBuilder();
            voltageQualified.setUpBuilder(upBuilder);
            voltageQualified.setDownBuilder(downBuilder);

            List<VoltU1_96> col_time$U = curve.getCOL_TIME$U();

            col_time$U.sort(Comparator.comparing(VoltU1_96::getU));
            List<VoltU1_96> voltU1_96s = col_time$U.stream().sorted(Comparator.comparing(VoltU1_96::getU)).collect(Collectors.toList());

            Set set = new HashSet();
            Collections.addAll(set, $24);
            //判断当前计量点是24个点还是96个点
            if (col_time$U.size() <= 24) {
                for (int i = 0; i < col_time$U.size(); i++) {
                    Integer u = col_time$U.get(i).getU();
                    set.add(u);
                }
                if (set.size() <= 24) {
                    voltageQualified.setDyCount(24);
                } else {
                    voltageQualified.setDyCount(96);
                }
            } else {
                voltageQualified.setDyCount(96);
            }

            //获取实采点数
            Integer dyPracticalCount = FormulaUtils.getDyPracticalCount(voltU1_96s);
            voltageQualified.setDyPCount(dyPracticalCount);

            logId = cdId;
            Date date = Optional.ofNullable(curve.getDATA_DATE())
                    .orElse(null);
            //相序标识
            String phase_flag = Optional.ofNullable(curve.getPHASE_FLAG())
                    .orElse(null);
            if (!phase_flag.equals("1")) {
                return null;
            }

            //计算用户
            String yh = yhMap.get(cdId);
            String pb = pbGxMap.get(cdId);

            if (pb != null) {
                //TODO 我认为现在这个地方vo重置，先都算配变的

                Gx gx = EntityUtils.StringToPbGx(pb);
                setAc(pbacMap, voltageQualified, gx, effectiveDataMap, yzpbMap);
                if (voltageQualified.getUp() == null || voltageQualified.getEffectiveDataUper() == null
                        || voltageQualified.getYzYhPbUper() == null) {
                    return null;
                }
                vo = pb(cdId, date, voltageQualified, voltU1_96s, gx);

            } else if (yh != null) {
                Gx gx = EntityUtils.StringToYhGx2(yh);
                setAc(acMap, voltageQualified, gx, effectiveDataMap, yzpbMap);

                if (voltageQualified.getUp() == null || voltageQualified.getEffectiveDataUper() == null
                        || voltageQualified.getYzYhPbUper() == null) {
                    log.info("阈值为空");
                    return null;
                }
                try {
                    vo = yh(cdId, date, voltageQualified, voltU1_96s, gx);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }


            if (ObjectUtil.isNull(vo)) {
                return null;
            }

            return vo;
        }else {
            return null;
        }
    }

    public static VoltageQualifiedVo sparkGetResult(CMS_VOLT_CURVE curve, Jedis jedis) {
        //测点id
        String cdId = curve.getMETER_ID();
        if (meterIdMap.get(cdId) != null) {
            meterIdMap.put(cdId, "");
        } else {
            return null;
        }
        Integer[] $24 = {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93};

        pointList = Arrays.asList($24);
        String logId = "";
        VoltageQualifiedVo vo = null;
        //初始化公共对象
        VoltageQualified voltageQualified = EntityUtils.initVoltageQualified();

        //越上限电压数组
        StringBuilder upBuilder = new StringBuilder();
        StringBuilder downBuilder = new StringBuilder();
        voltageQualified.setUpBuilder(upBuilder);
        voltageQualified.setDownBuilder(downBuilder);

        List<VoltU1_96> col_time$U = curve.getCOL_TIME$U();

        col_time$U.sort(Comparator.comparing(VoltU1_96::getU));


        Set set = new HashSet();
        Collections.addAll(set, $24);
        //判断当前计量点是24个点还是96个点
        if (col_time$U.size() <= 24) {
            for (int i = 0; i < col_time$U.size(); i++) {
                Integer u = col_time$U.get(i).getU();
                set.add(u);
            }
            if (set.size() == 24) {
                voltageQualified.setDyCount(24);
            } else {
                voltageQualified.setDyCount(96);
            }
        } else {
            voltageQualified.setDyCount(96);
        }

//        long u2 = System.currentTimeMillis();


        logId = cdId;
        Date date = Optional.ofNullable(curve.getDATA_DATE())
                .orElse(null);
        //相序标识
        String phase_flag = Optional.ofNullable(curve.getPHASE_FLAG())
                .orElse(null);
        if (!phase_flag.equals("1")) {
            return null;
        }

        //计算用户
        String yh = yhMap.get(cdId);
        String pb = pbGxMap.get(cdId);


        if (pb != null) {
            //TODO 我认为现在这个地方vo重置，先都算配变的

            Gx gx = EntityUtils.StringToPbGx(pb);
            setAc(pbacMap, voltageQualified, gx, effectiveDataMap, yzpbMap);
            if (voltageQualified.getUp() == null || voltageQualified.getEffectiveDataUper() == null
                    || voltageQualified.getYzYhPbUper() == null) {
                return null;
            }
            vo = pb(cdId, date, voltageQualified, col_time$U, gx);


        } else if (yh != null) {
            Gx gx = EntityUtils.StringToYhGx(yh);
            setAc(acMap, voltageQualified, gx, effectiveDataMap, yzpbMap);

            if (voltageQualified.getUp() == null || voltageQualified.getEffectiveDataUper() == null
                    || voltageQualified.getYzYhPbUper() == null) {
                log.info("阈值为空");
                return null;
            }
            try {
                vo = yh(cdId, date, voltageQualified, col_time$U, gx);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


        if (ObjectUtil.isNull(vo)) {
            return null;
        }

        return vo;
    }


    public static void setAc(Map<String, Double> acMap, VoltageQualified voltageQualified, Gx gx, Map<String, Double> effectiveDataMap, Map<String, Double> seriousnessMap) {
        if (acMap.containsKey(gx.getUp())) {
            Double up = acMap.get(gx.getUp());
            Double down = acMap.get(gx.getDown());
            voltageQualified.setUp(up);
            voltageQualified.setDown(down);
        }
        if (seriousnessMap.containsKey(gx.getUp())) {
            Double yzUper = seriousnessMap.get(gx.getUp());
            Double yzDown = seriousnessMap.get(gx.getDown());
            voltageQualified.setYzYhPbUper(yzUper);
            voltageQualified.setYzYhPbDown(yzDown);
        }
        if (effectiveDataMap.containsKey(gx.getUp())) {
            voltageQualified.setEffectiveDataUper(effectiveDataMap.get(gx.getUp()));
            voltageQualified.setEffectiveDataLower(effectiveDataMap.get(gx.getDown()));
        }
    }

    public static VoltageQualifiedVo yh(String cdId, Date date, VoltageQualified voltageQualified, List<VoltU1_96> u1_96List, Gx gx) throws ParseException {

        ArrayList<MaxAndMin> maxAndMins = new ArrayList<>();
        HashMap<String, Integer> blMap = new HashMap<>();
        blMap.put("AC02202", 1);
        blMap.put("AC03802", 1);
        blMap.put("AC00061", 60);
        blMap.put("AC00101", 100);
        blMap.put("AC00201", 200);
        blMap.put("AC00351", 350);
        blMap.put("AC00661", 660);
        blMap.put("AC01101", 1100);
        blMap.put("AC02201", 2200);
        blMap.put("AC03301", 3300);
        blMap.put("AC05001", 5000);
        //获取倍率 TODO
        boolean flag = true;

        /**
         * 判断基础电压是否需要修正
         * 96个点不正常点数大于50%
         */
        boolean yhMagnification = FormulaUtils.isYhMagnification(gx, u1_96List, voltageQualified);
        //1长期高 2长期低 3严重高  4严重低
        StringJoiner stringJoiner = new StringJoiner(",");

        for (int i = 0; i < u1_96List.size(); i++) {
            String v = u1_96List.get(i).getV();
            Integer u1 = u1_96List.get(i).getU();
            if (v != null && v.length() > 0) {
                Integer index = u1_96List.get(i).getU();
//                StringJoiner voltArray = voltageQualified.getVoltArray();
//                voltArray.add(u1_96List.get(i).getU()+":"+u1_96List.get(i).getV());
                Double u = Double.valueOf(v);
                /**
                 * 最大最小值 获取全部数据的最大最小值（包含无效数据和越限数据）
                 */
                if (flag) {
                    voltageQualified.setMax(u);
                    voltageQualified.setMin(u);
                    flag = false;
                }
                //判断当前电压等级是高压还是低压 电压值具体是多少 需不需要*根号三
                if (yhMagnification) {
                    //判断当前电压等级是高压还是低压 电压值具体是多少 需不需要*根号三
                    FormulaUtils.yhMagnification(voltageQualified, gx, blMap, u);
                }
                //无效也算实际采集数
                voltageQualified.setRealVoltagePoint(voltageQualified.getRealVoltagePoint() + 1);
                voltageQualified.setIndex(u1_96List.get(i).getU());
                FormulaUtils.IsVoltageQualified2(voltageQualified,u1,maxAndMins);
            }
        }
        List<MaxAndMin> maxAndMinList = maxAndMins.stream().sorted(Comparator.comparing(MaxAndMin::getVolt))
                .collect(Collectors.toList());

        MaxAndMin minVolt = null;
        MaxAndMin maxVolt = null;
        DateTime maxValueTime = null;
        DateTime minValueTime = null;
        if (maxAndMinList.size() > 0) {
            minVolt = maxAndMinList.get(0);
            maxVolt = maxAndMinList.get(maxAndMinList.size() - 1);
            minValueTime = DateUtil.offsetMinute(date, (minVolt.getIndex() - 1) * 15);
            maxValueTime = DateUtil.offsetMinute(date, (maxVolt.getIndex() - 1) * 15);
        }

        VoltageLevelEnum voltageLevelEnum = VoltageLevelEnum.valueOf(gx.getDydj());
//        Double           avg              = 0D;
//        if (voltageQualified.getNotNullPoint() != 0) {
//            avg = voltageQualified.getTotalU() / voltageQualified.getNotNullPoint();
//        }
        Double avg = FormulaUtils.avg(voltageQualified);
//        String pbArray = voltageQualified.getPbArray();
        String pbarrays = "";
//        if (pbArray != null && pbArray.length() > 1) {
//            pbarrays = pbArray.substring(0, pbArray.length() - 1);
//        }
        Integer dyCount = voltageQualified.getDyCount();
        Integer count = 0;
        if (dyCount != null && dyCount > 24) {
            count = 96;
        } else {
            count = 24;
        }

        voltageQualified.setDyCount(count);
        //设置用户异常类型 1-长期高 2-长期低 3-严重高 4-严重低
        FormulaUtils.consType(voltageQualified);
        FormulaUtils.consCsAndTime(voltageQualified);
//        ArrayList<Integer> monitoringTimeList = voltageQualified.getMonitoringTimeList();

        VoltageQualifiedVo voltageQualifiedVo = VoltageQualifiedVo.builder()
                .id(cdId)
                .sbName(gx.getUserName())
                .sbId(gx.getUserId())
                .dateTime(date)
                .dyCount(count.doubleValue())
                .uperTimeArray(voltageQualified.getUpBuilder().toString())
                .lowerTimeArray(voltageQualified.getDownBuilder().toString())
                .monitorTime(voltageQualified.getMonitorTime())
                .effectiveDataTime(voltageQualified.getEffectiveDataTime())
                .upTime(voltageQualified.getUpTime())
                .downTime(voltageQualified.getDownTime())
                .deviceType(Constant.SbTypeEnum.YH.getType().toString())
                .deviceLevel(Constant.SbLevelEnum.YH.getType())
                .pid(gx.getPid())
                .maxValue(Optional.ofNullable(maxVolt)
                        .orElseGet(MaxAndMin::new) // 如果 maxVolt 为 null，通过 Lambda 表达式生成一个默认的 Volt 对象
                        .getVolt())
                .minValue(Optional.ofNullable(minVolt)
                        .orElseGet(MaxAndMin::new) // 如果 maxVolt 为 null，通过 Lambda 表达式生成一个默认的 Volt 对象
                        .getVolt())
                .minValueTime(minValueTime)
                .maxValueTime(maxValueTime)
                .realVoltagePoint(voltageQualified.getRealVoltagePoint())
                .orgNo(gx.getOrgNo())
//                .orgName(gx.getOrgName())
                .avg(avg)
                .gridType(gx.getGridType())
                .consType(voltageQualified.getConsType())
                .pbArray(pbarrays)
                .highVoltage(voltageQualified.getHighVoltage().toString())
                .lowVoltage(voltageQualified.getLowVoltage().toString())
                .severeHighVoltage(voltageQualified.getSevereHighVoltage().toString())
                .severelyLowVoltage(voltageQualified.getSeverelyLowVoltage().toString())
                .highCs(voltageQualified.getHighCs())
                .highTime(voltageQualified.getHighTime())
                .lowCs(voltageQualified.getLowCs())
                .lowTime(voltageQualified.getLowTime())
                .severeHighCs(voltageQualified.getSevereHighCs())
                .severeHighTime(voltageQualified.getSevereHighTime())
                .severelyLowCs(voltageQualified.getSeverelyLowCs())
                .severelyLowTime(voltageQualified.getSeverelyLowTime())
//                .monitoringTimeArray(monitoringTimeList.toString())
//                .voltArray(voltageQualified.getVoltArray().toString())
                .build();
        voltageQualifiedVo.setVoltageLevel(VoltageLevelEnum.valueOf(gx.getDydj()).getCode());
        return voltageQualifiedVo;
    }
    public static VoltageQualifiedVo pb(String cdId, Date date, VoltageQualified voltageQualified, List<VoltU1_96> u1_96List, Gx gx) {

        /**
         * 连续两个及两个以上数据点都越限则判为越限，越限时间为（N-1）*采集间隔，一个点越限则不判为越限（前后数据正常情况）。
         */
        ArrayList<Integer> yxList = new ArrayList<>();
        ArrayList<MaxAndMin> maxAndMins = new ArrayList<>();

        boolean flag = true;
        boolean pbMagnification = FormulaUtils.isPbMagnification(voltageQualified, u1_96List);
        //1长期高 2长期低 3严重高  4严重低
        StringJoiner stringJoiner = new StringJoiner(",");
        for (int i = 0; i < u1_96List.size(); i++) {
            String v = u1_96List.get(i).getV();
            Integer u1 = u1_96List.get(i).getU();
            if (v != null && v.length() > 0) {
//                StringJoiner voltArray = voltageQualified.getVoltArray();
//                voltArray.add(u1_96List.get(i).getU()+":"+u1_96List.get(i).getV());
                Double u = Double.valueOf(v);
                if (flag) {
                    voltageQualified.setMax(u);
                    voltageQualified.setMin(u);
                    flag = false;
                }
                voltageQualified.setVoltage(u);
                if (pbMagnification) {
                    //判断配变需不需要*根号三
                    FormulaUtils.pbMagnification(voltageQualified, gx, u);
                }

                //无效也算实际采集数
                voltageQualified.setRealVoltagePoint(voltageQualified.getRealVoltagePoint() + 1);
                //如果当前是无效数据 则不统计 跳出当前循环
//                if (voltageQualified.getValid().equals("2")) {
//                    continue;
//                }
                //获取当前下标
                voltageQualified.setIndex(u1_96List.get(i).getU());
                /**
                 * 重庆配变全是220v
                 */
                FormulaUtils.pbCorrection(voltageQualified, u);
                FormulaUtils.IsVoltageQualified2(voltageQualified,u1,maxAndMins);
                FormulaUtils.pbYzYs(voltageQualified);
            }
        }

        List<MaxAndMin> maxAndMinList = maxAndMins.stream().sorted(Comparator.comparing(MaxAndMin::getVolt))
                .collect(Collectors.toList());
        MaxAndMin minVolt = null;
        MaxAndMin maxVolt = null;
        DateTime maxValueTime = null;
        DateTime minValueTime = null;
        if (maxAndMinList.size() > 0) {
            minVolt = maxAndMinList.get(0);
            maxVolt = maxAndMinList.get(maxAndMinList.size() - 1);
            minValueTime = DateUtil.offsetMinute(date, (minVolt.getIndex() - 1) * 15);
            maxValueTime = DateUtil.offsetMinute(date, (maxVolt.getIndex() - 1) * 15);
        }

        FormulaUtils.Pbcs(voltageQualified);

        VoltageLevelEnum voltageLevelEnum = VoltageLevelEnum.valueOf(gx.getDydj());

//        Double avg = 0D;
//        if (voltageQualified.getNotNullPoint() != 0) {
//            avg = voltageQualified.getTotalU() / voltageQualified.getNotNullPoint();
//        }
        Double avg = FormulaUtils.avg(voltageQualified);
        BigDecimal b = new BigDecimal(avg);
        Double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        Integer yzyxTime = voltageQualified.getYzyxTime();

        //是否是严重越上配变  严重越上时间大于60为严重越上配变
        String s = "0";
        if (yzyxTime > 60) {
            s = "1";
        }

        //电压波动率
        if (voltageQualified.getMax() == null) {
            voltageQualified.setMax(0D);
        }
        //电压波动率
        Double voltageFluctuation = FormulaUtils.voltageFluctuation(voltageQualified.getMax(), voltageQualified.getMin(), gx.getDydj());
//        String pbArray = voltageQualified.getPbArray();

        String pbarrays = "";
//        if (pbArray != null && pbArray.length() > 1) {
//            pbarrays = pbArray.substring(0, pbArray.length() - 1);
//        }

        Integer dyCount = voltageQualified.getDyCount();
        Integer count = 0;
        if (dyCount != null && dyCount > 24) {
            count = 96;
        } else {
            count = 24;
        }

//        ArrayList<Integer> monitoringTimeList = voltageQualified.getMonitoringTimeList();

        return VoltageQualifiedVo.builder()
                .id(cdId)
                .sbName(gx.getTranName())
                .sbId(gx.getPbId())
                .dateTime(date)
                .dyCount(count.doubleValue())
                .uperTimeArray(voltageQualified.getUpBuilder().toString())
                .lowerTimeArray(voltageQualified.getDownBuilder().toString())
                .monitorTime(voltageQualified.getMonitorTime())
                .upTime(voltageQualified.getUpTime())
                .downTime(voltageQualified.getDownTime())
                .deviceType(Constant.SbTypeEnum.PB.getType().toString())
                .deviceLevel(Constant.SbLevelEnum.PB.getType())
                .pid("")
                .maxValue(Optional.ofNullable(maxVolt)
                        .orElseGet(MaxAndMin::new) // 如果 maxVolt 为 null，通过 Lambda 表达式生成一个默认的 Volt 对象
                        .getVolt())
                .minValue(Optional.ofNullable(minVolt)
                        .orElseGet(MaxAndMin::new) // 如果 maxVolt 为 null，通过 Lambda 表达式生成一个默认的 Volt 对象
                        .getVolt())
                .minValueTime(minValueTime)
                .maxValueTime(maxValueTime)
                .realVoltagePoint(voltageQualified.getRealVoltagePoint())
                .orgNo(gx.getOrgNo())
//                .orgName(gx.getOrgName())
                .voltageLevel(voltageLevelEnum.getCode())
                .avg(f1)
                .effectiveDataTime(voltageQualified.getEffectiveDataTime())
                .seriousnessPb(s)
                .voltageFluctuation(voltageFluctuation)
                .pbArray(pbarrays)
                .pbcs(null)
                .pbtype(null)
                .gridType(gx.getGridType())
                .highCs(voltageQualified.getHighCs())
                .highTime(voltageQualified.getHighTime())
                .lowCs(voltageQualified.getLowCs())
                .lowTime(voltageQualified.getLowTime())
                .severeHighCs(voltageQualified.getSevereHighCs())
                .severeHighTime(voltageQualified.getSevereHighTime())
                .severelyLowCs(voltageQualified.getSeverelyLowCs())
                .severelyLowTime(voltageQualified.getSeverelyLowTime())
//                .monitoringTimeArray(monitoringTimeList.toString())
//                .voltArray(voltageQualified.getVoltArray().toString())
                .build();
    }


    /**
     * 设置电压最大最小值
     *
     * @param voltageQualified 电压vo
     */
    public static void setMaxAndMin(VoltageQualified voltageQualified, Integer index) {
        //判断电压最大最小值
        int offset = voltageQualified.getOffset();
        Double maxU = voltageQualified.getMax();
        Double minU = voltageQualified.getMin();

        // 处理最大和最小电压
//        if (offset == 1) {
//            voltageQualified.setMax(voltageQualified.getVoltage());
//            voltageQualified.setMin(voltageQualified.getVoltage());
//        }

        if (voltageQualified.getVoltage() > maxU) {
            voltageQualified.setMax(voltageQualified.getVoltage());
            voltageQualified.setMaxUOffset(offset);
        }

        if (voltageQualified.getVoltage() < minU) {
            voltageQualified.setMin(voltageQualified.getVoltage());
            voltageQualified.setMinUOffset(offset);
        }


        voltageQualified.setOffset(index);
    }

    public static void readMap(String pbgx, String yhgx, String yhpb, Map<String, Void> METER_IDS) throws Exception {

        log.info("加载完成阈值关系");
        //月份20220103
        String month = pbgx.substring(4, 6);

        //读取关系配置
        String[] headers = new String[]{"user_id", "volt_code", "meter_id", "org_no", "org_name", "user_name"};
        String filePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
        //填充用户到测点的关系map
        yhMap = CsvUtils.CsvToObject2(filePath, headers, month, yhgx, METER_IDS);
        log.info("加载完成用户测点关系: " + yhMap.size());

//        String[] pbHeaders = new String[]{"cdId", "pbId", "volt_code", "tran_name", "org_no", "grid_type", "equip_id", "edrl", "sbxh", "tyrq"};
//        String pbFilePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
//        //填充用户和台区的关系map
//        yhPidMap = CsvUtils.CsvToPb(pbFilePath, pbHeaders, yhpb);
//        log.info("加载完成用户台区关系: " + yhPidMap.size());
//
//        //填充配变到测点的关系map
//        pbGxMap = CsvUtils.CsvToPbCd(pbFilePath, pbHeaders, pbgx, month);
//        log.info("加载完成配变测点关系: " + pbGxMap.size());
    }

    //读取配置文件 加载关联关系
    public static void readProperties(String pbgx, String yhgx, String yhpb) throws Exception {
        String path = ReadHdfsFile.pbFilePath;
        String acPath = path + "ac.properties";
        PropertiesUtils.readProperties(acPath, acMap);

        String pbacPath2 = path + "pbac.properties";
        PropertiesUtils.readProperties(pbacPath2, pbacMap);

        //配变用户严重阈值
        String yzpbPath = path + "yzpb.properties";
        PropertiesUtils.readProperties(yzpbPath, yzpbMap);

        // 读取有效数据上限和下限
        String effectiveDataPath = path + "effectiveData.properties";
        PropertiesUtils.readProperties(effectiveDataPath, effectiveDataMap);


        log.info("加载完成阈值关系");
        //月份20220103
        String month = pbgx.substring(4, 6);

        //读取关系配置
        String[] headers = new String[]{"user_id", "volt_code", "meter_id", "org_no", "org_name", "user_name"};
        //填充用户到测点的关系map
        yhMap = CsvUtils.CsvToObject2(path, headers, month, yhgx, null);
        log.info("加载完成用户测点关系: " + yhMap.size());

        String[] pbHeaders = new String[]{"cdId", "pbId", "volt_code", "tran_name", "org_no", "grid_type", "equip_id", "edrl", "sbxh", "tyrq"};
        //填充用户和台区的关系map
//        yhPidMap = CsvUtils.CsvToPb(path, pbHeaders, yhpb);
//        log.info("加载完成用户台区关系: " + yhPidMap.size());

        //填充配变到测点的关系map
        pbGxMap = CsvUtils.CsvToPbCd(path, pbHeaders, pbgx, month);
        log.info("加载完成配变测点关系: " + pbGxMap.size());

    }

    public static void sparkReadProperties(String pbgx, String yhgx, String yhpb) throws Exception {
        String path = HdfsUtils.uriPathPrefix + "/conf/";
        String acPath = path + "ac.properties";
        PropertiesUtils.sparkReadProperties(acPath, acMap);

        String pbacPath2 = path + "pbac.properties";
        PropertiesUtils.sparkReadProperties(pbacPath2, pbacMap);

        //配变用户严重阈值
        String yzpbPath = path + "yzpb.properties";
        PropertiesUtils.sparkReadProperties(yzpbPath, yzpbMap);

        // 读取有效数据上限和下限
        String effectiveDataPath = path + "effectiveData.properties";
        PropertiesUtils.sparkReadProperties(effectiveDataPath, effectiveDataMap);


        log.info("加载完成阈值关系");
        //月份20220103
        String month = pbgx.substring(4, 6);

        //读取关系配置
        String[] headers = new String[]{"user_id", "volt_code", "meter_id", "org_no", "org_name", "user_name"};
        String csvPath = HdfsUtils.uriPathPrefix + "/conf";
        //填充用户到测点的关系map
        yhMap = CsvUtils.sparkCsvToObject(csvPath, headers, month, yhgx, null);
        log.info("加载完成用户测点关系: " + yhMap.size());

        String[] pbHeaders = new String[]{"cdId", "pbId", "volt_code", "tran_name", "org_no", "grid_type", "equip_id", "edrl", "sbxh", "tyrq"};
        //填充用户和台区的关系map
//        yhPidMap = CsvUtils.sparkCsvToPb(csvPath, pbHeaders, yhpb);
//        log.info("加载完成用户台区关系: " + yhPidMap.size());

        //填充配变到测点的关系map
        pbGxMap = CsvUtils.sparkCsvToPbCd(csvPath, pbHeaders, pbgx, month);
        log.info("加载完成配变测点关系: " + pbGxMap.size());

    }

    public static void readPropertiesHdfs(String pbgx, String yhgx, String yhpb) throws Exception {
        String acPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "ac.properties";
        PropertiesUtils.readProperties(acPath, acMap);

        String pbacPath2 = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "pbac.properties";
        PropertiesUtils.readProperties(pbacPath2, pbacMap);

        //配变用户严重阈值
        String yzpbPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "yzpb.properties";
        PropertiesUtils.readProperties(yzpbPath, yzpbMap);

        // 读取有效数据上限和下限
        String effectiveDataPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "effectiveData.properties";
        PropertiesUtils.readProperties(effectiveDataPath, effectiveDataMap);


        log.info("加载完成阈值关系");
        //月份20220103
        String month = pbgx.substring(4, 6);

        //读取关系配置
        String[] headers = new String[]{"user_id", "volt_code", "meter_id", "org_no", "org_name", "user_name"};
        String filePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
        //填充用户到测点的关系map
        yhMap = CsvUtils.CsvToObject2(filePath, headers, month, yhgx, null);
        log.info("加载完成用户测点关系: " + yhMap.size());

        String[] pbHeaders = new String[]{"cdId", "pbId", "volt_code", "tran_name", "org_no", "grid_type", "equip_id", "edrl", "sbxh", "tyrq"};
        String pbFilePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
        //填充用户和台区的关系map
//        yhPidMap = CsvUtils.CsvToPb(pbFilePath, pbHeaders, yhpb);
//        log.info("加载完成用户台区关系: " + yhPidMap.size());

        //填充配变到测点的关系map
        pbGxMap = CsvUtils.CsvToPbCd(pbFilePath, pbHeaders, pbgx, month);
        log.info("加载完成配变测点关系: " + pbGxMap.size());

    }


    public static void main(String[] args) {
        String name = "1,2,3";

        String[] split = name.split(",");


        try {
            split[3]="4";
        }catch (ArrayIndexOutOfBoundsException e){
            split = Arrays.copyOf(split, split.length + 1);
            split[3]="4";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String s:split){
            stringBuilder.append(s).append(",");
        }
        System.out.println(stringBuilder.toString());

    }


}
